package com.cn.fw4j.util.crypto;

import javax.crypto.*;
import javax.crypto.spec.DESKeySpec;

import java.security.*;

/**
 * CryptoHelper
 * @author murenchao
 *
 */
public class CryptoHelper {
	/**
	 * MD5 and SHA1
	 * @param type
	 * @param value
	 * @return
	 */
	public static String encode(String type,String value){
		try {
			char[] hexDigits ={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
			MessageDigest md = MessageDigest.getInstance(type);
			byte[] digest = md.digest(value.getBytes());
			int count = digest.length;
			char[] res = new char[count*2];
			for(int i=0,k=0;i<count;i++){
				byte b0 = digest[i];
				res[k++] = hexDigits[b0 >> 4 & 0xf];
				res[k++] = hexDigits[b0 & 0xf];
			}
			return new String(res);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return null;
	}
	public static class DES{
		/**
		 * 加密
		 * @param pwd String 密码
		 * @param value String 加密的内容
		 * @return String
		 */
		public static byte[] encrypt(String pwd,byte[] value){
			try {
				SecureRandom random = new SecureRandom();
				DESKeySpec  deskey = new DESKeySpec(pwd.getBytes());
				SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
				SecretKey securekey = keyFactory.generateSecret(deskey);
				Cipher cipher = Cipher.getInstance("DES");
				cipher.init(Cipher.ENCRYPT_MODE,securekey,random);
				return cipher.doFinal(value);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		}
		public static byte[] decrypt(String pwd,byte[] value){
			try {
				SecureRandom random = new SecureRandom();
				DESKeySpec  deskey = new DESKeySpec(pwd.getBytes());
				SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
				SecretKey securekey = keyFactory.generateSecret(deskey);
				Cipher cipher = Cipher.getInstance("DES");
				cipher.init(Cipher.DECRYPT_MODE,securekey,random);
				return cipher.doFinal(value);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		}
	}
	public static class AES{
	}

	public static void main(String[] a){
		System.out.println(encode("md5","aa"));
		System.out.println(encode("SHA1","aa"));
		byte[] c = DES.encrypt("12345678","aaa".getBytes());
		System.out.println(new String(c));
		System.out.println(new String(DES.decrypt("12345678", c)));
		
	}
}
